import { Menu } from 'antd'
import React, { useState, useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { RouterType } from '@/router/types'
import route from '../../router'
import { SiderMenu } from '@/types/sidebar'
function getMenu(arr: RouterType[] = [], path = ''): SiderMenu[] | undefined {
  if (arr && arr.length) {
    return arr
      .map((item: RouterType) => {
        if (item.children?.length === 1) {
          const child = item.children[0]
          return {
            key:
              item.path !== '/'
                ? item.path + '/' + child.path
                : '/' + child.path,
            label: child.name,
            children: undefined,
          }
        } else {
          return {
            key:
              path && path !== '/' ? path + '/' + item.path : path + item.path,
            label: item.name,
            children: getMenu(item.children, item.path),
          }
        }
      })
      .filter((item: RouterType) => !item.hiddren)
  } else {
    return undefined
  }
}
export default function Layout() {
  const [items, setItems] = useState<SiderMenu[] | undefined>([])
  useEffect(() => {
    console.log(getMenu(route.routes))
    setItems(getMenu(route.routes))
  }, [])
  const location = useLocation()
  const [current, setCurrent] = useState(location.pathname)
  useEffect(() => {
    // 当路由路径发生变化时，更新selectedKeys
    setCurrent(location.pathname)
  }, [location])
  const navigate = useNavigate()
  const onClick = (e: { key: string }) => {
    // setCurrent(e.key)
    navigate(e.key)
  }
  return (
    <Menu
      onClick={onClick}
      selectedKeys={[current]}
      mode="inline"
      items={items}
    ></Menu>
  )
}
